package com.polaris.live.common.basic

import androidx.activity.result.ActivityResultCaller
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContract

abstract class BaseActivityLauncher<INPUT, OUTPUT>(
    caller: ActivityResultCaller,
    contract: ActivityResultContract<INPUT, OUTPUT>
) {

    private val launcher: ActivityResultLauncher<INPUT>
    private var callback: ((OUTPUT) -> Unit)? = null

    init {
        launcher = caller.registerForActivityResult(contract) {
            if (callback != null) {
                callback?.invoke(it)
                callback = null
            }
        }
    }

    fun launch(input: INPUT, callback: ((OUTPUT) -> Unit)? = null) {
        this.callback = callback
        launcher.launch(input)
    }
}